// 销售统计相关功能

// 从本地存储加载销售记录
function loadSalesRecords() {
    try {
        const salesRecordsJson = localStorage.getItem('salesRecords') || '[]';
        const records = JSON.parse(salesRecordsJson);
        if (!Array.isArray(records)) {
            throw new Error('销售记录格式不正确');
        }
        return records;
    } catch (e) {
        console.error('加载销售记录失败:', e);
        localStorage.setItem('salesRecords', JSON.stringify([]));
        return [];
    }
}

// 保存销售记录到本地存储
function saveSalesRecords(records) {
    localStorage.setItem('salesRecords', JSON.stringify(records));
}

// 初始化销售记录（如果不存在）
function initSalesRecords() {
    if (!localStorage.getItem('salesRecords')) {
        const sampleRecords = [
            {
                date: new Date().toISOString(),
                customerName: '测试客户',
                totalAmount: 150.50,
                products: [
                    { name: '排骨', price: 35.0, weight: 2.5, amount: 87.5 },
                    { name: '瘦肉', price: 27.0, weight: 2.35, amount: 63.45 }
                ]
            },
            {
                date: new Date(Date.now() - 86400000).toISOString(),
                customerName: '示例客户',
                totalAmount: 200.00,
                products: [
                    { name: '猪脚', price: 22.0, weight: 5.0, amount: 110.0 },
                    { name: '三层', price: 28.0, weight: 3.21, amount: 89.88 }
                ]
            }
        ];
        saveSalesRecords(sampleRecords);
    }
}

// 根据日期范围过滤销售记录
function filterSalesRecordsByDate(records, dateRange) {
    const now = new Date();
    let startDate;
    let endDate;

    switch (dateRange) {
        case 'today':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            break;
        case 'yesterday':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            break;
        case 'week':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay());
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            break;
        case 'month':
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
            break;
        case 'all':
            return records;
        default:
            return records;
    }

    return records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= startDate && recordDate < endDate;
    });
}

// 计算统计信息
function calculateStatistics(records) {
    const totalRevenue = records.reduce((sum, record) => sum + record.totalAmount, 0);
    const totalOrders = records.length;
    const avgOrderAmount = totalOrders > 0 ? totalRevenue / totalOrders : 0;
    
    // 从localStorage加载商品成本价
      const productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};
      
      // 调试日志：打印成本价数据概览
      console.log('从localStorage加载的成本价数据:', productCostPrices);
      console.log('成本价数据数量:', Object.keys(productCostPrices).length);
      
      // 调试日志：打印所有商品的成本价
      console.log('所有商品的成本价:');
      for (const [productName, costPrice] of Object.entries(productCostPrices)) {
        console.log(`${productName}: ${costPrice}`);
      }
      
      // 调试日志：打印关键商品的成本价
      console.log('排骨成本价:', productCostPrices['排骨'] || '未找到');
      console.log('五花肉成本价:', productCostPrices['五花肉'] || '未找到');
    
    // 计算实际总利润
    let totalProfit = 0;
    let missingCostCount = 0;
    let missingCostProducts = [];
    
    records.forEach(record => {
        record.products.forEach(product => {
            // 优先使用商品记录中的成本价，如果没有则使用全局成本价数据
            const costPrice = product.costPrice || productCostPrices[product.name] || 0;
            if (costPrice === 0) {
                missingCostCount++;
                if (!missingCostProducts.includes(product.name)) {
                    missingCostProducts.push(product.name);
                }
            }
            
            // 确保价格和重量是有效的数字
            const price = parseFloat(product.price) || 0;
            const weight = parseFloat(product.weight) || 0;
            const productProfit = (price - costPrice) * weight;
            // 打印每个商品的利润计算详情
            console.log(`商品: ${product.name}, 价格: ${price}, 成本价: ${costPrice}, 重量: ${weight}, 利润: ${productProfit}`);
            totalProfit += productProfit;
        });
    });

    console.log('总利润计算结果:', totalProfit);
    console.log('缺少成本价的商品数量:', missingCostCount);
    console.log('缺少成本价的商品列表:', missingCostProducts);

    return {
        totalRevenue,
        totalOrders,
        avgOrderAmount,
        totalProfit
    };
}

// 更新统计卡片
function updateStatisticsCards(statistics) {
    const totalRevenueEl = document.getElementById('total-revenue');
    const totalOrdersEl = document.getElementById('total-orders');
    const avgOrderAmountEl = document.getElementById('avg-order-amount');
    const totalProfitEl = document.getElementById('total-profit');
    
    if (totalRevenueEl) totalRevenueEl.textContent = statistics.totalRevenue.toFixed(2);
    if (totalOrdersEl) totalOrdersEl.textContent = statistics.totalOrders;
    if (avgOrderAmountEl) avgOrderAmountEl.textContent = statistics.avgOrderAmount.toFixed(2);
    if (totalProfitEl) totalProfitEl.textContent = statistics.totalProfit.toFixed(2);
}

// 更新统计数据的函数
function updateStatisticsByDateRange() {
    const dateRange = document.getElementById('date-filter').value;
    const allRecords = loadSalesRecords();
    const filteredRecords = filterSalesRecordsByDate(allRecords, dateRange);
    updateSalesRecordsTable(filteredRecords);
    updateStatisticsCards(calculateStatistics(filteredRecords));
}

// 更新销售记录表格
function updateSalesRecordsTable(records) {
    const tableBody = document.getElementById('sales-records-body');
    if (!tableBody) return;

    tableBody.innerHTML = '';

    if (records.length === 0) {
        const emptyRow = document.createElement('tr');
        emptyRow.innerHTML = '<td colspan="4" style="text-align: center;">暂无销售记录</td>';
        tableBody.appendChild(emptyRow);
        return;
    }

    records.forEach((record, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${new Date(record.date).toLocaleString()}</td>
            <td>${record.customerName}</td>
            <td class="amount">${record.totalAmount.toFixed(2)}</td>
            <td><button class="btn view-details-btn" data-index="${index}">查看详情</button></td>
        `;
        tableBody.appendChild(row);
    });
}

// 测试函数：检查localStorage中的成本价数据
function testCostPriceData() {
  console.log('=== 成本价数据测试开始 ===');
  
  // 直接从localStorage读取成本价数据
  const storedCostPrices = localStorage.getItem('productCostPrices');
  console.log('localStorage中是否存在成本价数据:', storedCostPrices !== null);
  
  if (storedCostPrices) {
    const parsedCostPrices = JSON.parse(storedCostPrices);
    console.log('解析后的成本价数据:', parsedCostPrices);
    console.log('成本价数据数量:', Object.keys(parsedCostPrices).length);
    
    // 打印所有商品的成本价
    console.log('所有商品的成本价列表:');
    for (const [productName, costPrice] of Object.entries(parsedCostPrices)) {
      console.log(`${productName}: ${costPrice}`);
    }
  }
  
  console.log('=== 成本价数据测试结束 ===');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 调用测试函数检查成本价数据
    testCostPriceData();
    
    initSalesRecords();
    const initialRecords = loadSalesRecords();
    updateSalesRecordsTable(initialRecords);
    updateStatisticsCards(calculateStatistics(initialRecords));

    // 为日期选择器添加change事件
    const dateFilter = document.getElementById('date-filter');
    if (dateFilter) dateFilter.addEventListener('change', updateStatisticsByDateRange);

    // 为查询按钮添加点击事件
    const filterBtn = document.getElementById('filter-btn');
    if (filterBtn) filterBtn.addEventListener('click', updateStatisticsByDateRange);

    // 页面加载时自动应用默认日期筛选
    updateStatisticsByDateRange();
});